<script lang="ts" setup>
import type { InputOnInput } from '@uni-helper/uni-app-types'
import { IconPath, PagePath } from '@/common/constants'

const props = withDefaults(
  defineProps<{
    /**
     * 搜索栏类型
     * @type -  search 为可操作的搜索
     *       - bar 展示的元素
     *
     * @default bar
     */
    type: 'search' | 'bar'
    modelValue: string
    placeholderText: string
  }>(),
  {
    type: 'bar',
    modelValue: '',
    placeholderText: PLACE_ENTER_CONTENT,
  },
)
const emits = defineEmits(['onSearch', 'onChangeValue', 'update:modelValue'])

/** 搜索内容 */
const searchContent = ref(props.modelValue)

/** 跳转到search */
const goToSearch = () => {
  uni.navigateTo({
    url: PagePath.SEARCH,
  })
}

/**
 * 修改搜索文本
 * @param event
 */
const inputSearchValue: InputOnInput = (event) => {
  searchContent.value = event.detail.value
  emits('update:modelValue', searchContent.value)
}

/** 搜索事件 */
const onSearch = () => {
  if (searchContent.value.trim() === '') {
    showSimpleToast(PLACE_ENTER_CONTENT)
  }

  // 触发父组件的方法
  emits('onSearch', searchContent.value)
}
</script>

<template>
  <!-- 搜索栏组件 -->
  <view v-if="type === 'bar'" class="search" @click="goToSearch">
    <view class="search-content search-content--bar">
      <image :src="IconPath.SEARCH_LIGHT" mode="scaleToFill" class="search-icon--bar" />
      <text class="search-text">
        {{ placeholderText }}
      </text>
    </view>
  </view>

  <view v-else class="search">
    <view class="search-content">
      <image :src="IconPath.SEARCH_GREY" mode="scaleToFill" class="search-icon" />
      <input

        v-model="searchContent"
        type="text" confirm-type="search" :placeholder="placeholderText" focus
        @input="inputSearchValue" @confirm="onSearch"
      >
    </view>
  </view>
</template>

<style lang="scss" scoped>
.search {
  flex: 1;
  height: 80rpx;

  &-content {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 10rpx;
    height: 100%;
    background-color: $bg-gray;
    border-radius: 40rpx;

    &--bar {
      background-color: $bg-white-opacity-5;
    }
  }

  &-icon {
    width: 40rpx;
    height: 40rpx;
    fill: $uni-text-color-grey;

    &--bar {
      width: 40rpx;
      height: 40rpx;
    }
  }

  &-text {
    font-size: $font-size-base;
    color: white;
  }
}
</style>
